<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\user\model\MeetingLogModel;
use app\user\model\UserOrderModel;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;
use EasyWeChat\Factory;
use think\Db;
use think\Log;
use think\Validate;

class PublicController extends HomeBaseController
{

    // 用户头像api
    public function avatar()
    {
        $id = $this->request->param("id", 0, "intval");
        $user = UserModel::get($id);

        $avatar = '';
        if (!empty($user)) {
            $avatar = cmf_get_user_avatar_url($user['avatar']);
            if (strpos($avatar, "/") === 0) {
                $avatar = $this->request->domain() . $avatar;
            }
        }

        if (empty($avatar)) {
            $cdnSettings = cmf_get_option('cdn_settings');
            if (empty($cdnSettings['cdn_static_root'])) {
                $avatar = $this->request->domain() . "/static/images/headicon.png";
            } else {
                $cdnStaticRoot = rtrim($cdnSettings['cdn_static_root'], '/');
                $avatar = $cdnStaticRoot . "/static/images/headicon.png";
            }

        }

        return redirect($avatar);
    }

    public function callback()
    {
        $config = [
            // 必要配置
            'app_id' => 'wxd8f1bbf96330e02c',
            'mch_id' => '1509241831',
            'key' => 'JCkvTDnGYbcRu0g2maYnC7XBLfKRRXIh',   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
            'key_path' => 'path/to/your/key',      // XXX: 绝对路径！！！！

            'notify_url' => '',     // 你也可以在下单时单独设置来想覆盖它
        ];

        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write($message);
            $orderModel = new UserOrderModel();

            $order = $orderModel->where('out_trade_no', $message['out_trade_no'])->find();

            if (!$order || $order->pay_status == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $order->pay_time = time(); // 更新支付时间为当前时间
                    $order->pay_status = 1;
                    if ($order->type == 0) {

                        $this->userHandlePay($order['uid']);
                    } else if ($order->type == 1) {
                        $this->meetingHandle($order);
                    }
                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    $order->pay_status = 0;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); // 保存订单

            return true; // 返回处理完成
        });

        $response->send();
    }

    protected function meetingHandle($order)
    {
        $meetingLogModel = new  MeetingLogModel();
        $log = $meetingLogModel->where('order_id', $order['id'])->where('status', 0)->find();
        if($log){
            $log->status = 1;
            $log->save();

        }

    }

    protected function userHandlePay($uid)
    {
        $userModel = new UserModel();
        $user = $userModel->where('id', $uid)->find();
        if ($user) {
            if ($user['vip'] == 0) {
                $user['vip'] = 1;
            }
            $user['vip_time'] = $user['vip_time'] + strtotime("+1 year");
            $user->save();
        }
    }


    public function getCity($province_id)
    {
        $citys = Db::name('cities')->where('provinceid', $province_id)->select();
        $this->success('获取成功', null, $citys);
    }

    public function getArea($city_id)
    {
        $areas = Db::name('areas')->where('cityid', $city_id)->select();
        $this->success('获取成功', null, $areas);
    }
}
